package cn.tedu.spring_security.dao;

import cn.tedu.spring_security.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDaoJdbcImpl implements UserDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    RowMapper<User> rowMapper = (rs, rowNum) -> {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setRoles(rs.getString("roles"));
        return user;
    };

    @Override
    public User findUserByUsername(String username) {
        String sql = "select * from user where username=?";
        try {
            return jdbcTemplate.queryForObject(sql, rowMapper, username);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("没有查询到用户信息");
            return null;
        }
    }

    @Override
    public List<User> findAll() {
        /**
         * 使用rowMapper对象将查询结果映射为实体对象
         */
        String sql = "Select * from user";
        try {
            return jdbcTemplate.query(sql, rowMapper);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("没有查询到用户信息");
            return null;
        }
    }
}
